import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _map from "lodash/map";
import _isFunction from "lodash/isFunction";

var _dec, _dec2, _dec3, _dec4, _dec5, _dec6, _class;

import React from 'react';
import { Icon, Layout, Spin, List, Popover, Tabs } from 'antd';
import { Bind } from 'lodash-decorators';
import { connect } from 'dva';
import { Link, Redirect, Route, Switch } from 'dva/router';
import uuid from 'uuid/v4';
import getTabRoutes from "../../../components/Router";
import Exception from "../../../components/Exception";
import Icons from "../../../components/Icons";
import { cleanCache } from "../../../components/CacheComponent";
import intl from "../../../utils/intl";
import { isPromise } from "../../../utils/utils";
import { closeTab, getBeforeMenuTabRemove, getTabFromKey, menuTabEventManager, openTab } from "../../../utils/menuTab";
import styles from "./index.less?modules";
var Content = Layout.Content;
var TabPane = Tabs.TabPane;

var DefaultNotFound = function DefaultNotFound() {
  return /*#__PURE__*/React.createElement(Exception, {
    type: "404",
    style: {
      minHeight: 500,
      height: '80%'
    },
    linkElement: Link
  });
};

var EMPTY_ROUTE = function EMPTY_ROUTE() {
  return null;
};
/**
 * 菜单数据结构改变 只有菜单有path,目录没有path
 * 所有的菜单必须有 服务前缀 `/服务前缀/...功能集合/功能/...子功能`
 * 根据菜单取得重定向地址.
 */


var getRedirect = function getRedirect(item) {
  var redirectData = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : [];

  if (item && item.children) {
    // 目录
    for (var i = 0; i < item.children.length; i++) {
      getRedirect(item.children[i], redirectData);
    }

    return redirectData;
  }

  if (item && item.path) {
    // 菜单
    var menuPaths = item.path.split('/');

    if (!menuPaths[0]) {
      menuPaths = menuPaths.slice(1, menuPaths.length);
    }

    var menuPath = '';

    var _loop = function _loop(_i) {
      menuPath += "/".concat(menuPaths[_i]);
      var from = menuPath;
      var to = "".concat(menuPath, "/").concat(menuPaths[_i + 1]);
      var exist = redirectData.some(function (route) {
        return route.from === from;
      });

      if (!exist) {
        redirectData.push({
          from: from,
          to: to
        });
      }
    };

    for (var _i = 0; _i < menuPaths.length - 1; _i++) {
      _loop(_i);
    }
  }
};

window.addEventListener('fullscreenchange', function () {
  if (!document.fullscreenElement) {
    var node = document.querySelector(".cpaas-fullscreen");

    if (node) {
      node.classList.remove('cpaas-fullscreen');
    }
  }
});
var DefaultMenuTabs = (_dec = Bind(), _dec2 = Bind(), _dec3 = Bind(), _dec4 = Bind(), _dec5 = Bind(), _dec6 = Bind(), (_class = /*#__PURE__*/function (_React$Component) {
  _inherits(DefaultMenuTabs, _React$Component);

  var _super = _createSuper(DefaultMenuTabs);

  function DefaultMenuTabs(props) {
    var _this;

    _classCallCheck(this, DefaultMenuTabs);

    _this = _super.call(this, props);

    _this.onTabEdit = function (targetKey, action) {
      _this[action](targetKey);
    };

    _this.state = {
      contextMenuVisibleKey: '',
      // 显示的右键菜单对应的 tab
      contextMenuVisible: false // 是否显示 右键菜单

    };
    _this.refreshKeyMap = new Map();
    return _this;
  }
  /**
   * 切换 tab
   * @param {string} activeKey - menuTab 的 key
   */


  _createClass(DefaultMenuTabs, [{
    key: "onTabChange",
    value: function onTabChange(activeKey) {
      // const { history } = this.props;
      openTab(getTabFromKey(activeKey));
    }
  }, {
    key: "remove",
    value:
    /**
     * 关闭 tab
     */
    function remove(targetKey) {
      var onBeforeHandler = getBeforeMenuTabRemove(targetKey);

      if (_isFunction(onBeforeHandler)) {
        var isShouldDelete = onBeforeHandler();

        if (isPromise(isShouldDelete)) {
          isShouldDelete.then( // 关闭tab
          function () {
            cleanCache(targetKey);
            closeTab(targetKey);
          });
        } else if (isShouldDelete !== false) {
          cleanCache(targetKey);
          closeTab(targetKey);
        }
      } else {
        cleanCache(targetKey);
        closeTab(targetKey);
      }
    }
    /**
     * 清除 contextMenu 的信息
     */

  }, {
    key: "clearContextMenuVisible",
    value: function clearContextMenuVisible() {
      this.setState({
        contextMenuVisibleKey: '',
        contextMenuVisible: false
      });
    }
    /**
     * 在 render 时 使用了 arrow function, 所以不需要 @Bind()
     * 触发右键菜单的事件
     * @param {Object} pane - tab
     * @param {Boolean} visible - 显示或隐藏
     */

  }, {
    key: "handleContextMenuTrigger",
    value: function handleContextMenuTrigger(pane, visible) {
      this.setState({
        contextMenuVisibleKey: pane.key,
        contextMenuVisible: visible
      });
    }
    /**
     * 关闭除了当前 tab 的 所有可关闭的tab, 如果新的 tabs 不包含 active tab 则 打开当前 tab
     * @param {object} pane - menuTab 数据
     */

  }, {
    key: "handleMenuTabCloseOthers",
    value: function handleMenuTabCloseOthers(pane, e) {
      e.stopPropagation();
      var _this$props = this.props,
          removeOtherMenuTab = _this$props.removeOtherMenuTab,
          _this$props$tabs = _this$props.tabs,
          tabs = _this$props$tabs === void 0 ? [] : _this$props$tabs,
          activeTabKey = _this$props.activeTabKey;
      var removeTabs = tabs.filter(function (t) {
        return t.key !== pane.key && t.closable;
      });
      this.clearContextMenuVisible();
      removeOtherMenuTab({
        tab: pane
      }).then(function (nextActiveTabKey) {
        if (nextActiveTabKey !== activeTabKey) {
          openTab(getTabFromKey(nextActiveTabKey));
        }

        removeTabs.forEach(function (t) {
          cleanCache(t.key);
          menuTabEventManager.emit('close', {
            tabKey: t.key
          });
        });
      });
    }
    /**
     * 关闭除了当前 tab 的 所有可关闭的tab, 如果新的 tabs 不包含 active tab 则 打开当前 tab
     * @param {object} pane - menuTab 数据
     */

  }, {
    key: "handleMenuTabCloseLeft",
    value: function handleMenuTabCloseLeft(pane, e) {
      e.stopPropagation();
      var _this$props2 = this.props,
          removeSomeMenuTab = _this$props2.removeSomeMenuTab,
          _this$props2$tabs = _this$props2.tabs,
          tabs = _this$props2$tabs === void 0 ? [] : _this$props2$tabs,
          activeTabKey = _this$props2.activeTabKey;
      var removeTabs = tabs.slice(0, tabs.findIndex(function (t) {
        return t.key === pane.key;
      })).filter(function (i) {
        return i.closable;
      }).map(function (j) {
        return j.key;
      });
      this.clearContextMenuVisible();
      removeSomeMenuTab({
        removeTabs: removeTabs
      }).then(function () {
        if (pane.key !== activeTabKey) {
          openTab(getTabFromKey(pane.key));
        }

        removeTabs.forEach(function (t) {
          cleanCache(t.key);
          menuTabEventManager.emit('close', {
            tabKey: t.key
          });
        });
      });
    }
    /**
     * 关闭除了当前 tab 的 所有可关闭的tab, 如果新的 tabs 不包含 active tab 则 打开当前 tab
     * @param {object} pane - menuTab 数据
     */

  }, {
    key: "handleMenuTabCloseRight",
    value: function handleMenuTabCloseRight(pane, e) {
      e.stopPropagation();
      var _this$props3 = this.props,
          removeSomeMenuTab = _this$props3.removeSomeMenuTab,
          _this$props3$tabs = _this$props3.tabs,
          tabs = _this$props3$tabs === void 0 ? [] : _this$props3$tabs,
          activeTabKey = _this$props3.activeTabKey;
      var removeTabs = tabs.slice(tabs.findIndex(function (t) {
        return t.key === pane.key;
      }) + 1).filter(function (i) {
        return i.closable;
      }).map(function (j) {
        return j.key;
      });
      this.clearContextMenuVisible();
      removeSomeMenuTab({
        removeTabs: removeTabs
      }).then(function () {
        if (pane.key !== activeTabKey) {
          openTab(getTabFromKey(pane.key));
        }

        removeTabs.forEach(function (t) {
          cleanCache(t.key);
          menuTabEventManager.emit('close', {
            tabKey: t.key
          });
        });
      });
    }
    /**
     * 关闭所有可关闭的tab, 打开最靠近的 !closable 的tab
     * @param {object} pane - menuTab 数据
     */

  }, {
    key: "handleMenuTabCloseAll",
    value: function handleMenuTabCloseAll(pane, e) {
      e.stopPropagation();
      var _this$props4 = this.props,
          removeAllMenuTab = _this$props4.removeAllMenuTab,
          _this$props4$tabs = _this$props4.tabs,
          tabs = _this$props4$tabs === void 0 ? [] : _this$props4$tabs,
          activeTabKey = _this$props4.activeTabKey;
      var removeTabs = tabs.filter(function (t) {
        return t.closable;
      });
      this.clearContextMenuVisible();
      removeAllMenuTab({
        tab: pane
      }).then(function (nextActiveTabKey) {
        if (nextActiveTabKey !== activeTabKey) {
          openTab(getTabFromKey(nextActiveTabKey));
        }

        removeTabs.forEach(function (t) {
          cleanCache(t.key);
          menuTabEventManager.emit('close', {
            tabKey: t.key
          });
        });
      });
    }
    /**
     * 刷新当前 tab
     * @param {object} pane - menuTab 数据
     */

  }, {
    key: "handleMenuTabRefresh",
    value: function handleMenuTabRefresh(pane, e) {
      e.stopPropagation();
      this.clearContextMenuVisible();
      this.refreshKeyMap.set(pane.key, uuid());
      menuTabEventManager.emit('refresh', {
        tabKey: pane.key
      });
      this.forceUpdate();
    }
    /**
     * 全屏当前 tab
     * @param {object} pane - menuTab 数据 page-container
     */

  }, {
    key: "handleMenuTabFullScreen",
    value: function handleMenuTabFullScreen(pane, e) {
      e.stopPropagation();
      var _this$props5 = this.props,
          activeTabKey = _this$props5.activeTabKey,
          menuLayout = _this$props5.menuLayout;
      this.clearContextMenuVisible();

      if (!document.fullscreenElement) {
        if (menuLayout === 'horizontal') {
          var node = document.querySelector(".cpaas-layout");
          node.classList.add('cpaas-fullscreen');
        } else if (menuLayout === 'side') {
          var _node = document.querySelector(".cpaas-side-layout-container");

          _node.classList.add('cpaas-fullscreen');
        } else if (menuLayout === 'side-all') {
          var _node2 = document.querySelector(".cpaas-common-layout-container");

          _node2.classList.add('cpaas-fullscreen');
        } else {
          var _node3 = document.querySelector(".cpaas-normal-container");

          _node3.classList.add('cpaas-fullscreen');
        }

        if (document.documentElement.requestFullscreen) {
          document.documentElement.requestFullscreen();
        } else if (document.documentElement.msRequestFullscreen) {
          document.documentElement.msRequestFullscreen();
        } else if (document.documentElement.mozRequestFullScreen) {
          document.documentElement.mozRequestFullScreen();
        } else if (document.documentElement.webkitRequestFullscreen) {
          document.documentElement.webkitRequestFullscreen();
        }
      }

      if (pane.key !== activeTabKey) {
        openTab(getTabFromKey(pane.key));
      }
    }
  }, {
    key: "getBaseRedirect",
    value: function getBaseRedirect() {
      // According to the url parameter to redirect
      // 这里是重定向的,重定向到 url 的 redirect 参数所示地址
      var urlParams = new URL(window.location.href);
      var redirect = urlParams.searchParams.get('redirect'); // Remove the parameters in the url

      if (redirect) {
        urlParams.searchParams.delete('redirect');
        window.history.replaceState(null, 'redirect', urlParams.href);
      } else {
        var _this$props$routerDat = this.props.routerData,
            routerData = _this$props$routerDat === void 0 ? {} : _this$props$routerDat; // get the first authorized route path in routerData
        // const authorizedPath = Object.keys(routerData).find(
        //   item => check(routerData[item].authority, item) && item !== '/'
        // );

        var authorizedPath = Object.keys(routerData).find(function (item) {
          return item !== '/';
        });
        return authorizedPath;
      }

      return redirect;
    }
  }, {
    key: "render",
    value: function render() {
      var _this2 = this;

      var _this$props6 = this.props,
          activeTabKey = _this$props6.activeTabKey,
          language = _this$props6.language,
          _this$props6$NotFound = _this$props6.NotFound,
          NotFound = _this$props6$NotFound === void 0 ? DefaultNotFound : _this$props6$NotFound,
          _this$props6$tabs = _this$props6.tabs,
          tabs = _this$props6$tabs === void 0 ? [] : _this$props6$tabs,
          _this$props6$menu = _this$props6.menu,
          menu = _this$props6$menu === void 0 ? [] : _this$props6$menu,
          layoutLoading = _this$props6.layoutLoading,
          pathname = _this$props6.pathname,
          _this$props6$routerDa = _this$props6.routerData,
          routerData = _this$props6$routerDa === void 0 ? {} : _this$props6$routerDa,
          _this$props6$extraRig = _this$props6.extraRight,
          extraRight = _this$props6$extraRig === void 0 ? null : _this$props6$extraRig;

      if (layoutLoading) {
        return /*#__PURE__*/React.createElement("div", {
          style: {
            textAlign: 'center'
          }
        }, /*#__PURE__*/React.createElement(Spin, {
          size: "large"
        }));
      }

      var _this$state = this.state,
          contextMenuVisibleKey = _this$state.contextMenuVisibleKey,
          _this$state$contextMe = _this$state.contextMenuVisible,
          contextMenuVisible = _this$state$contextMe === void 0 ? false : _this$state$contextMe;
      var redirectData = [{
        from: '/',
        to: '/workplace'
      }]; // 根目录需要跳转到工作台

      menu.forEach(function (item) {
        getRedirect(item, redirectData);
      });
      var bashRedirect = this.getBaseRedirect();
      return /*#__PURE__*/React.createElement(React.Fragment, null, /*#__PURE__*/React.createElement(Switch, null, _map(redirectData, function (item) {
        return /*#__PURE__*/React.createElement(Redirect, {
          key: item.from,
          exact: true,
          from: item.from,
          to: item.to
        });
      }), bashRedirect ? /*#__PURE__*/React.createElement(Redirect, {
        exact: true,
        from: "/",
        to: bashRedirect
      }) : null, menu.length === 0 ? null : /*#__PURE__*/React.createElement(Route, {
        render: EMPTY_ROUTE
      })), /*#__PURE__*/React.createElement(Tabs, {
        hideAdd: true,
        onChange: this.onTabChange,
        activeKey: activeTabKey,
        type: "editable-card",
        onEdit: this.onTabEdit,
        tabBarExtraContent: extraRight,
        className: styles['menu-tabs']
      }, _map(tabs, function (pane, index) {
        return /*#__PURE__*/React.createElement(TabPane, {
          closable: pane.closable,
          tab: /*#__PURE__*/React.createElement(Popover, {
            overlayClassName: "default-menu-tabs-context-menu",
            content: /*#__PURE__*/React.createElement(List, {
              size: "small"
            }, (tabs.length > 2 || pane.key === '/workplace') && tabs.length !== 1 && /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabCloseOthers(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "close-other",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon"
            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.closeOther').d('关闭其他'))), pane.key !== '/workplace' && index !== 1 && /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabCloseLeft(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "close-all",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon"
            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.closeLeft').d('关闭左侧'))), tabs.length - 1 !== index && /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabCloseRight(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "close-all",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon"
            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.closeRight').d('关闭右侧'))), tabs.length !== 1 && /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabCloseAll(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "close-all",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon"
            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.closeAll').d('关闭全部'))), /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabFullScreen(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "full-screen",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon" // style={{ lineHeight: 'inherit', fontSize: '14px' }}

            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.fullScreen').d('全屏'))), pane.key === activeTabKey && /*#__PURE__*/React.createElement(List.Item, {
              onClick: function onClick(e) {
                _this2.handleMenuTabRefresh(pane, e);
              },
              className: "default-menu-tabs-context-menu-item"
            }, /*#__PURE__*/React.createElement(Icons, {
              type: "refresh",
              size: 14,
              className: "default-menu-tabs-context-menu-item-icon"
            }), /*#__PURE__*/React.createElement("span", {
              className: "default-menu-tabs-context-menu-item-text"
            }, intl.get('cpaas.common.button.refresh').d('刷新')))),
            title: null,
            trigger: "contextMenu",
            visible: pane.key === contextMenuVisibleKey && contextMenuVisible,
            onVisibleChange: function onVisibleChange(visible) {
              _this2.handleContextMenuTrigger(pane, visible);
            }
          }, pane.path === '/workplace' ? /*#__PURE__*/React.createElement("span", null, /*#__PURE__*/React.createElement(Icon, {
            type: pane.icon,
            key: "icon"
          }), language ? pane.title && intl.get(pane.title).d(pane.title) : '...') : /*#__PURE__*/React.createElement("span", null, language ? pane.title && intl.get(pane.title).d(pane.title) : '...')),
          key: pane.key
        }, /*#__PURE__*/React.createElement(Content, {
          className: "page-container",
          key: _this2.refreshKeyMap.get(pane.key)
        }, getTabRoutes({
          pane: pane,
          routerData: routerData,
          NotFound: NotFound,
          pathname: pathname,
          menu: menu,
          activeTabKey: activeTabKey
        })));
      })));
    }
  }]);

  return DefaultMenuTabs;
}(React.Component), (_applyDecoratedDescriptor(_class.prototype, "handleMenuTabCloseOthers", [_dec], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabCloseOthers"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleMenuTabCloseLeft", [_dec2], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabCloseLeft"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleMenuTabCloseRight", [_dec3], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabCloseRight"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleMenuTabCloseAll", [_dec4], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabCloseAll"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleMenuTabRefresh", [_dec5], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabRefresh"), _class.prototype), _applyDecoratedDescriptor(_class.prototype, "handleMenuTabFullScreen", [_dec6], Object.getOwnPropertyDescriptor(_class.prototype, "handleMenuTabFullScreen"), _class.prototype)), _class));

function mapStateToProps(_ref) {
  var _ref$global = _ref.global,
      global = _ref$global === void 0 ? {} : _ref$global,
      _ref$user = _ref.user,
      user = _ref$user === void 0 ? {} : _ref$user,
      routing = _ref.routing;
  var _user$currentUser = user.currentUser,
      currentUser = _user$currentUser === void 0 ? {} : _user$currentUser;
  var _currentUser$menuLayo = currentUser.menuLayout,
      menuLayout = _currentUser$menuLayo === void 0 ? 'default-layout' : _currentUser$menuLayo;
  return {
    activeTabKey: global.activeTabKey,
    tabs: global.tabs,
    menu: global.menu,
    routerData: global.routerData,
    language: global.language,
    layoutLoading: global.layoutLoading,
    menuLayout: menuLayout,
    pathname: routing && routing.location.pathname
  };
}

function mapDispatchToProps(dispatch) {
  return {
    removeSomeMenuTab: function removeSomeMenuTab(payload) {
      return dispatch({
        type: 'global/removeSomeMenuTab',
        payload: payload
      });
    },
    removeOtherMenuTab: function removeOtherMenuTab(payload) {
      return dispatch({
        type: 'global/removeOtherMenuTab',
        payload: payload
      });
    },
    removeAllMenuTab: function removeAllMenuTab(payload) {
      return dispatch({
        type: 'global/removeAllMenuTab',
        payload: payload
      });
    }
  };
}

export default connect(mapStateToProps, mapDispatchToProps, null, {
  pure: false
})(DefaultMenuTabs);